package com.lottery.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lottery.common.util.Constant;
import com.lottery.web.model.Account;
import com.lottery.web.model.AgentPlayer;
import com.lottery.web.service.PlayerMoneyService;
import com.lottery.web.service.UserMgrService;

/**
 * 用户管理
 * @author linzhimou
 * @since 2016年10月17日
 */
@Controller
@RequestMapping("/user")
public class UserMgrController extends BaseController{

	private static Logger logger = Logger.getLogger(UserMgrController.class);
	
	@Resource
	private UserMgrService userService;
	
	@Resource
	private PlayerMoneyService playerMoneyService;

	/**查询用户信息
	 * 管理员可以查询所有用户；
	 * 代理可以查询自己、下级代理、玩家；
	 * 玩家仅能查询自己的信息
	 * @param account
	 * @return
	 */
	@RequestMapping("/info")
	@ResponseBody
	public String userInfo(String userCode, HttpSession session){
		try{
			//如果userCode为空，表示查询自己的个人信息
			Account userInfo = (Account) session.getAttribute(Constant.USER);
			//查询用户金额
			userInfo.setAmount(this.playerMoneyService.getPlayerAmount(userInfo.getUserCode()));
			
			return jsonResult(userInfo);
			
		} catch (Exception ex){
			logger.error("error", ex);
			return errorResult("查询用户信息出错");
		}
		
	}
	
	/**检查用户名是否存在*/
	@RequestMapping("/checkName")
	@ResponseBody
	public String checkUserName(@RequestParam String userName){
		try{
			int count = userService.checkUserName(userName);
			if(count > 0)
				return errorResult("该用户名已被使用");
		} catch (Exception ex){
			logger.error("error", ex);
			return errorResult("查询用户名出错");
		}
		return jsonResult(null);
	}
	
	/**新增用户*/
	@RequestMapping("/add")
	@ResponseBody
	public String addUser(Account newUser, HttpSession session){
		//校验newUser
		
		//设置userCode
		Account currentUser = (Account) session.getAttribute(Constant.USER);
		String newUserCode = getUserCode(currentUser, newUser);
		newUser.setUserCode(newUserCode);
		//用户所属层级，处于当前用户的下一级
		newUser.setLayer(currentUser.getLayer() + 1);
		
		try{
			AgentPlayer agentPlayer = null;
			//如果新用户是玩家，保存代理-玩家关系
			if(newUser.getRole().equals(Constant.PLAYER)){
				agentPlayer = new AgentPlayer();
				String agentCode = (String) session.getAttribute(Constant.USERCODE);
				agentPlayer.setAgent(agentCode);
				agentPlayer.setPlayer(newUserCode);
			}
			
			userService.addUser(newUser, agentPlayer);
			
		} catch (Exception ex){
			logger.error("addUser error", ex);
			return errorResult("新增用户出错");
		}
		
		return jsonResult(null);
	}
	
	/**
	 * 生成用户编码
	 * @param currentUser 当前用户
	 * @param account	新增用户
	 * @return
	 */
	private String getUserCode(Account currentUser, Account newUser){
		String userCode = "";
		if(currentUser.getRole().equals(Constant.ADMIN)){
			//如果当前用户是管理员，开一级代理
			userCode = "AG_" + userService.getSeqValue(Constant.AGENT_SEQ);
		}else if(newUser.getRole().equals(Constant.AGENT)){
			//如果新增的用户是代理，拼接上层代理code作为前缀 
			userCode = currentUser.getUserCode() + "_" + 
							userService.getSeqValue(Constant.AGENT_SEQ);
		}else {
			//玩家与代理相同
			userCode = currentUser.getUserCode() + "_P" + 
							userService.getSeqValue(Constant.PLAYER_SEQ);
		}
		
		return userCode;
	}
	
	/**
	 * 修改密码
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 */
	@RequestMapping("/modifyPwd")
	@ResponseBody
	public String modifyPassword(@RequestBody Map<String, String> params, HttpSession session){
		
		String oldPwd = params.get("oldPwd");
		String newPwd = params.get("newPwd");
		if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd))
			return errorResult("密码为空");
		
		Account currentUser = (Account) session.getAttribute(Constant.USER);
		currentUser.setPassword(oldPwd);
		try{
			//查询旧密码是否正确
			Account user = userService.getUser(currentUser);
			if(user != null){
				Account newUserInfo = new Account();
				newUserInfo.setUserCode(currentUser.getUserCode());
				newUserInfo.setPassword(newPwd);
				userService.updataUser(newUserInfo);
			} else {
				return errorResult("旧密码错误");
			}
		} catch (Exception ex){
			logger.error("error", ex);
			return errorResult("修改密码出错");
		}
		
		return jsonResult(null);
	}
	
	@RequestMapping("/getUserLotteryForms")
	@ResponseBody
	/**
	 * 盈亏统计报表接口
	 * @param session
	 * @return
	 */
	public String getUserLotteryForms(HttpSession session){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String [] queryTypeArr = {"today","yesterday","total"};
		Account currentUser = (Account) session.getAttribute(Constant.USER);
		for (int i = 0; i < queryTypeArr.length; i++) {
			String queryType = queryTypeArr[i];
			Map<String,Object> queryRetMap = userService.getUserLotteryForms(currentUser.getUserCode(), queryType);
			resultMap.put(queryType, queryRetMap);
		}
		return super.jsonResult(resultMap);
	}
	
	@RequestMapping("/queryAgentPlayer")
	@ResponseBody
	public String queryAgentPlayer(@RequestParam Map<String, Object> param, HttpSession session) {
		logger.info("begin query agent player...param: " + param);
		try {
			Account userInfo = (Account) session.getAttribute(Constant.USER);
			String userCode = (String) param.get("userCode");
			String isDirect = (String) param.get("isDirect");
			Map<String, Object> queryParam = new HashMap<String, Object>();
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if ("player".equals(userInfo.getRole())) {
				if (StringUtils.isEmpty(isDirect)) {
					return super.errorResult("无此用户");
				} else if ("N".equals(isDirect.toUpperCase())) {
					return super.errorResult("权限不足");
				} else if ("Y".equals(isDirect.toUpperCase())) {
					queryParam.put("player", userInfo.getUserCode());
					Map<String, Object> result = this.userService.queryAgentPlayer(queryParam);
					resultMap.put("userCode", result.get("agent"));
				}
			} else if ("agent".equals(userInfo.getRole())) {
				if (StringUtils.isNotEmpty(userCode)) {
					queryParam.put("agent", userInfo.getUserCode());
					queryParam.put("player", userCode);
					Map<String, Object> result = this.userService.queryAgentPlayer(queryParam);
					resultMap.put("userCode", result.get("player"));
				} else if ("Y".equals(isDirect.toUpperCase())) {
					queryParam.put("player", userInfo.getUserCode());
					Map<String, Object> result = this.userService.queryAgentPlayer(queryParam);
					if (null == result) {
						return super.errorResult("没有上级代理");
					}
					resultMap.put("userCode", result.get("agent"));
				} else {
					return super.errorResult("无此用户");
				}
			} else if ("admin".equals(userInfo.getRole())) {
				resultMap.put("userCode", userCode);
			}
			logger.info("end query agent player result: " + resultMap);
			return super.jsonResult(resultMap);
		} catch (Exception e) {
			logger.error("query agent player exception: " + e.getMessage());
			return super.errorResult("系统异常");
		}
	}
	
	@RequestMapping("/queryUsers")
	@ResponseBody
	public String queryUsers(Map<String, Object> param, HttpSession session) {
		logger.info("begin query users... param: " + param);
		try {
			Account userInfo = (Account) session.getAttribute(Constant.USER);
			if ("player".equals(userInfo.getRole())) {
				return super.errorResult("权限不足");
			}
			Map<String, Object> queryParam = new HashMap<String, Object>();
			queryParam.put("userCode", userInfo.getUserCode());
			queryParam.put("userRole", userInfo.getRole());
			queryParam.put("userName", param.get("userName"));
			List<Map<String, Object>> userList = this.userService.queryUsers(queryParam);
			logger.info("query users result: " + userList);
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("userList", userList);
			return super.jsonResult(resultMap);
		} catch (Exception e) {
			logger.equals("query users exception: " + e.getMessage());
			return super.errorResult("系统异常");
		}
	}
	
	
	public static void main(String[] args) {
		int a = 2147483647;
		System.out.println(a + 1 < a );
	}
}
